import { defineStore } from "pinia";
import type { UserInfo } from "./types/type";
import { Names } from "./store-namespace";
import { Local } from "../utils/storage"; //storage
import router from "../router/index"; //vue-router的路由跳转方法
import { USER_INFO } from "./constant/cacheKey"; //本地缓存key值
import { _get, _post, _put, _delete, http } from "../utils/axios";
import { UserProfile } from "@/api/backend/index";
import qs from "qs";

export const useUserInfo = defineStore(Names.User, {
  state: (): any => {
    return {
      userId: 0,
      userName: "研发",
      nickName: "",
      email: "",
      avatar: "",
      loginIp: "",
      loginDate: "",
      createTime: "",
      phonenumber: "",
      companyid: 0,
      deptId: 0,
      sex: "",
    };
  },
  getters: {},
  actions: {
    //清空token
    removeToken() {},
    //赋值用户信息
    dataFill(state: UserInfo) {
      this.$state = state;
    },
    /**
     * 退出登录刷新refreshToken
     * 成功之后移除localstorage的userInfo的值刷新页面
     */

    logout() {
      // _post(Apis.postLougout, {refresh_token: userInfo.getToken('refresh')}, "json", "").then((res) => {
      //   if (res.code == 1) {
      //     Local.remove(USER_INFO);
      router.go(-1); //0刷新页面 -1 或者back()为后退
      //   }
      // });
    },
    //修改个人资料
    changeUserProfile(data: any) {
      return new Promise((resolve, reject) => {
        _put(UserProfile, data, "json", "")
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    //用户重置密码
    updatePwdByUser(data: any) {
      return new Promise((resolve, reject) => {
        _put(
          UserProfile +
            "/updatePwd?" +
            qs.stringify(data, { arrayFormat: "repeat" }),
          {},
          "",
          ""
        )
          .then((res) => {
            console.log(res);
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
  },
  persist: {
    key: USER_INFO,
  },
});
